<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="classificationName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
        </div>
        <div class="head-container">
          <el-tree :data="classificationOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode"
                   ref="tree" default-expand-all @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <!-- 搜索工作栏 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="物料编号" prop="itemNo">
            <el-input v-model="queryParams.itemNo" placeholder="请输入物料编号" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入备品备件名称" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="queryParams.specification" placeholder="请输入规格型号" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="标签码" prop="labelingCode">
            <el-input v-model="queryParams.labelingCode" placeholder="请输入标签码" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                      v-hasPermi="['ems:spares:create']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                      v-hasPermi="['ems:spares:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </el-col>
    </el-row>


    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="ID">
              <span>{{ props.row.id }}</span>
            </el-form-item>
             <el-form-item label="物料编号">
              <span>{{ props.row.itemNo }}</span>
            </el-form-item>
             <el-form-item label="名称">
              <span>{{ props.row.name }}</span>
            </el-form-item>
             <el-form-item label="规格型号">
              <span>{{ props.row.specification }}</span>
            </el-form-item>
             <el-form-item label="库存数量">
              <span>{{ props.row.amount }}</span>
            </el-form-item>
            
             <el-form-item label="上限">
              <span>{{ props.row.upperLimit }}</span>
            </el-form-item>
             <el-form-item label="下限">
              <span>{{ props.row.lowerLimit }}</span>
            </el-form-item>
             <el-form-item label="采购周期">
              <span>{{ props.row.cycle }}</span>
              <dict-tag :type="DICT_TYPE.COMMON_TIME_TYPE" :value="props.row.cycleUnit" />
            </el-form-item>
             <el-form-item label="更换周期">
              <span>{{ props.row.changeCycle }}</span>
              <dict-tag :type="DICT_TYPE.COMMON_TIME_TYPE" :value="props.row.changeCycleUnit" />
            </el-form-item>
             <el-form-item label="品牌">
              <span>{{ props.row.brand }}</span>
            </el-form-item>
             <el-form-item label="仓库">
              <span>{{ props.row.store.name }}</span>
            </el-form-item>
             <el-form-item label="单价">
              <span>{{ props.row.price == null ? null : parseFloat(props.row.price / 100).toFixed(2) }}</span>
            </el-form-item>
             <el-form-item label="标签码">
              <span>{{ props.row.labelingCode }}</span>
            </el-form-item>
             <el-form-item label="状态">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="props.row.status" />
            </el-form-item>
            <el-form-item label="附件">
              <a :href="props.row.enclosure" target="_blank" rel="noopener noreferrer">
                {{ props.row.enclosure }}
              </a>
            </el-form-item>
             <el-form-item label="备注">
              <span>{{ props.row.remarks }}</span>
            </el-form-item>
             <el-form-item label="创建时间">
              <span>{{ parseTime(props.row.createTime) }}</span>
            </el-form-item>
             <el-form-item label="更新时间">
              <span>{{ parseTime(props.row.updateTime) }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="物料编号" align="center" prop="itemNo" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="库存数量" align="center" prop="amount" />
      <el-table-column label="上限" align="center" prop="upperLimit" />
      <el-table-column label="下限" align="center" prop="lowerLimit" />
      <el-table-column label="采购周期" align="center" prop="cycle" >
        <template slot-scope="scope">
          <span>{{ scope.row.cycle }}</span>
          <dict-tag :type="DICT_TYPE.COMMON_TIME_TYPE" :value="scope.row.cycleUnit" />
        </template>
      </el-table-column>
      <el-table-column label="更换周期" align="center" prop="changeCycle" >
        <template slot-scope="scope">
          <span>{{ scope.row.changeCycle }}</span>
          <dict-tag :type="DICT_TYPE.COMMON_TIME_TYPE" :value="scope.row.changeCycleUnit" />
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="仓库" align="center" prop="store.name" />
      <el-table-column label="单价" align="center" prop="price" >
        <template slot-scope="scope">
          {{ scope.row.price == null ? null : parseFloat(scope.row.price / 100).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="标签码" align="center" prop="labelingCode" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ems:spares:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ems:spares:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编号" prop="itemNo">
          <el-input v-model="form.itemNo" placeholder="请输入物料编号" :disabled="itemNoEdit">
            <el-button slot="append" icon="el-icon-edit" @click="handleItemNoEdit">编辑</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入备品备件名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="amount">
              <el-input-number v-model="form.amount" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上限" prop="upperLimit">
              <el-input-number v-model="form.upperLimit" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限" prop="lowerLimit">
              <el-input-number v-model="form.lowerLimit" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购周期" prop="cycle">
              <el-input-number v-model="form.cycle" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="cycleUnit">
              <el-select v-model="form.cycleUnit" placeholder="请选择单位">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_TIME_TYPE)"
                          :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="更换周期" prop="changeCycle">
              <el-input-number v-model="form.changeCycle" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="changeCycleUnit">
              <el-select v-model="form.changeCycleUnit" placeholder="请选择单位">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_TIME_TYPE)"
                          :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="classificationId">
              <treeselect v-model="form.classificationId" :options="classificationOptions" :show-count="true" :clearable="false"
                              placeholder="请选择归属分类" :normalizer="normalizer"/>
            </el-form-item>
              </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="storeId">
              <treeselect v-model="form.storeId" :options="storeOptions" :show-count="true" :clearable="false"
                              placeholder="请选择归属分类" :normalizer="normalizer"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" >
             <template slot="append">分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="标签码" prop="labelingCode">
          <el-input v-model="form.labelingCode" placeholder="请输入标签码" />
        </el-form-item>
        <el-form-item label="附件" prop="enclosure">
          <!-- <upload v-model="form.enclosure" /> -->
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            :headers="upload.headers" 
            :action="upload.url" 
            :data="upload.data" 
            :disabled="upload.isUploading"
            :on-change="handleFileChange"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
            <div v-if="form.enclosure" slot="tip" class="el-upload__tip">
                {{form.enclosure}}
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" type="textarea"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createSpares, updateSpares, deleteSpares, getSpares, getSparesPage, exportSparesExcel } from "@/api/ems/spares";
import {listSimpleClassifications} from "@/api/ems/classification";
import {listSimpleStores} from "@/api/ems/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getAccessToken} from "@/utils/auth";
import Upload from "@/components/Upload";
import { completion } from "@/utils";

export default {
  name: "Spares",
  components: {Treeselect, Upload},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 备品备件列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        itemNo: null,
        name: null,
        specification: null,
        labelingCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemNo: [{ required: true, message: "物料编号不能为空", trigger: "blur" }],
        name: [{ required: true, message: "备品备件名称不能为空", trigger: "blur" }],
        specification: [{ required: true, message: "规格型号不能为空", trigger: "blur" }],
        classificationId: [{ required: true, message: "类别id不能为空", trigger: "blur" }],
        storeId: [{ required: true, message: "仓库id不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "change" }],
      },
      // 分类树选项
      classificationOptions: undefined,
      storeOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分类名称
      classificationName: undefined,
      storeName: undefined,
      defaultProps: {
        children: "children",
        label: "name"
      },
      upload: {
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
        headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
        data: {} // 上传的额外数据，用于文件名
      },
      // 编辑物料编号
      itemNoEdit: true,
      itemNo: undefined
    };
  },
  watch: {
    // 根据名称筛选分类树
    classificationName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getSparesPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
      return this.list
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        itemNo: undefined,
        name: undefined,
        specification: undefined,
        amount: undefined,
        upperLimit: undefined,
        lowerLimit: undefined,
        cycle: undefined,
        cycleUnit: undefined,
        changeCycle: undefined,
        changeCycleUnit: undefined,
        brand: undefined,
        classificationId: undefined,
        storeId: undefined,
        price: undefined,
        labelingCode: undefined,
        enclosure: undefined,
        image: undefined,
        remarks: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加备品备件";
      // 处理查询参数
      const params = {
        pageNo: 1,
        pageSize: 10,
        itemNo: null,
        name: null,
        specification: null,
        labelingCode: null
        };
      // 初始化物料编号
      getSparesPage(params).then(response => {
        if(response.data.length != 0) {
          let no = Number(response.data.list[0].itemNo.slice(2))
          this.form.itemNo = 'BP' + completion(no + 1, 9)
        } else this.form.itemNo = 'BP000000001'
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSpares(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改备品备件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateSpares(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSpares(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除备品备件编号为"' + id + '"的数据项?').then(function() {
          return deleteSpares(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有备品备件数据项?').then(() => {
          this.exportLoading = true;
          return exportSparesExcel(params);
        }).then(response => {
          this.$download.excel(response, '备品备件.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.classificationId = data.id;
      this.getList();
    },
    /** 查询分类下拉树结构 + 岗位下拉 */
    getTreeselect() {
      listSimpleClassifications().then(response => {
        // 处理 classificationOptions 参数
        this.classificationOptions = [];
        this.classificationOptions.push(...this.handleTree(response.data, "id"));
      });
      listSimpleStores().then(response => {
        // 处理 storeOptions 参数
        this.storeOptions = [];
        this.storeOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 格式化分类的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
      this.upload.data.path = file.name;
    },
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.form.enclosure = response.data
      // 清理
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
      // this.getList();
    },
    getDictData(dictType, value) {
      return this.getDictData(dictType, value)
    },
    // 编辑物料编号
    handleItemNoEdit() {
      if(!this.itemNoEdit) {
        this.itemNoEdit = true
      } else this.itemNoEdit = false
    } 
  }
};
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>